<template>
  <div>
    <!-- 运营工单 -->
    <div class="box">
      <div class="header">
        <!-- 查询 -->
        <el-form :inline="true" :model="queryObj" class="demo-form-inline">
          <el-form-item label="工单编号:">
            <el-input v-model="queryObj.taskCode" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="工单状态:">
            <el-select v-model="queryObj.status" placeholder="请选择">
              <el-option label="待办" :value="1" />
              <el-option label="进行" :value="2" />
              <el-option label="取消" :value="3" />
              <el-option label="完成" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              class="cha"
              @click="onSubmit"
            >查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="body">
        <!-- 新建 -->
        <div class="body-btn">
          <el-button
            type="warning"
            class="xin"
            icon="el-icon-circle-plus-outline"
            @click="dialogVisible = true"
          >
            新建
          </el-button>
          <el-button
            type="warning"
            plain
            class="gong"
            @click="disposition = true"
          >工单配置</el-button>
        </div>

        <!-- 新增工单 -->
        <el-dialog title="新增工单" :visible.sync="dialogVisible" width="500px">
          <el-form ref="form" :model="form" :rules="rules">
            <el-form-item
              label="设备编号："
              label-width="120px"
              prop="innerCode"
            >
              <el-input
                v-model="form.innerCode"
                style="width: 280px"
                placeholder="请输入"
                maxlength="15"
                show-word-limit
                @change="built"
              />
            </el-form-item>
            <el-form-item
              label="工单类型："
              label-width="120px"
              prop="productType"
            >
              <el-select
                v-model="form.productType"
                style="width: 280px"
                placeholder="请选择"
              >
                <el-option label="补货工单" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="补货数量：" label-width="120px">
              <el-link
                type="primary"
                :underline="false"
                @click="Replenishment"
              ><i class="el-icon-edit-outline" />补货清单</el-link>
            </el-form-item>
            <el-form-item label="运营人员：" label-width="120px" prop="userId">
              <el-select
                v-model="form.userId"
                style="width: 280px"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in user"
                  :key="item.taskId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注" label-width="120px" prop="desc">
              <el-input
                v-model="form.desc"
                type="textarea"
                style="width: 280px"
                placeholder="请输入备注（不超过40字）"
                maxlength="40"
                show-word-limit
              />
            </el-form-item>
          </el-form>
          <div slot="footer" style="margin-right: 150px">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="warning" @click="submit">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 补货清单 -->
        <el-dialog title="补货详情" :visible.sync="manifest" width="500px">
          <el-table
            v-loading="loading"
            :data="replenishmentlist"
            style="width: 100%"
            :header-cell-style="{ background: '#f8fafd' }"
          >
            <el-table-column
              prop="channelCode"
              label="货道编号"
              align="center"
            />
            <el-table-column
              prop="sku.skuName"
              label="商品名称"
              align="center"
            />
            <el-table-column
              prop="currentCapacity"
              label="当前数量"
              align="center"
            />
            <el-table-column label="还可添加" align="center">
              <template #default="{ row }">
                <div>{{ row.maxCapacity }}</div>
              </template>
            </el-table-column>
            <el-table-column label="补满数量" align="center">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.quantity"
                  controls-position="right"
                  :min="0"
                  :max="row.maxCapacity - row.currentCapacity"
                  style="width: 90px"
                  @change="handleChange"
                />
              </template> </el-table-column></el-table>
          <div slot="footer" style="margin-right: 150px">
            <el-button
              @click="
                manifest = false;
                dialogVisible = true;
              "
            >取 消</el-button>
            <el-button
              type="warning"
              @click="
                manifest = false;
                dialogVisible = true;
              "
            >确 定</el-button>
          </div>
        </el-dialog>

        <!-- 补货详情 -->
        <el-dialog
          title="补货详情"
          :visible.sync="restockDetails"
          width="500px"
        >
          <el-table
            v-loading="loading"
            :data="detaillist"
            style="width: 100%"
            :header-cell-style="{ background: '#f8fafd' }"
          >
            <el-table-column
              prop="channelCode"
              label="货道编号"
              align="center"
            />
            <el-table-column prop="sku.skuName" label="商品" align="center" />
            <el-table-column
              prop="currentCapacity"
              label="补货数量"
              align="center"
            />
          </el-table>
        </el-dialog>

        <!-- 工单配置 -->
        <el-dialog
          title="工单配置"
          :visible.sync="disposition"
          width="500px"
          :rules="rule"
        >
          <el-form :model="sum">
            <el-form-item label="补货警戒线：" label-width="120px" prop="sum">
              <el-input-number
                v-model="num"
                controls-position="right"
                :min="0"
                :max="50"
                style="width: 300px"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" style="margin-right: 150px">
            <el-button @click="disposition = false">取 消</el-button>
            <el-button
              type="warning"
              @click="configureCommits"
            >确 定</el-button>
          </div>
        </el-dialog>

        <!-- 表格数据 -->
        <el-table
          v-loading="loading"
          :data="list"
          style="width: 100%"
          :header-cell-style="{ background: '#f8fafd' }"
        >
          <el-table-column
            prop="index"
            label="序号"
            width="100"
            align="center"
          />
          <el-table-column
            prop="taskCode"
            label="工单编号"
            width="150"
            align="center"
          />
          <el-table-column
            prop="innerCode"
            width="100"
            label="设备编号"
            align="center"
          />
          <el-table-column
            prop="taskType.typeName"
            label="工单类型"
            align="center"
          />
          <el-table-column label="工单方式" align="center">
            <template #default="{ row }">
              <span>
                {{
                  row.createType === 0
                    ? "自动"
                    : row.createType === 1
                      ? "手动"
                      : "无"
                }}
              </span>
            </template></el-table-column>
          <el-table-column
            prop="taskStatusTypeEntity.statusName"
            label="工单状态"
            align="center"
          />
          <el-table-column
            prop="userName"
            width="100"
            label="运营人员"
            align="center"
          />
          <el-table-column label="创建日期" width="180" align="center">
            <template v-slot="{ row }">
              <span>
                {{
                  row.createTime.substring(0, 10) +
                    " " +
                    row.createTime.substring(11, 19)
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button type="text" @click="detail(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 详情弹窗 -->
        <el-dialog title="工单详情" :visible.sync="seeDetails" width="600px">
          <div v-if="flag">
            <div class="tickets">
              <div style="display: flex; align-items: center">
                <img
                  src=""
                  alt=""
                >
                <div style="margin-left: 20px">代办</div>
              </div>
              <div style="margin-right: 60px">
                <img
                  src="https://likede2-admin.itheima.net/img/pic_1.834b274c.png"
                  alt=""
                >
              </div>
            </div>
            <el-row :gutter="20" style="margin: 20px">
              <el-col :span="12">设备编号：{{ details?.innerCode }}</el-col>
              <el-col :span="12">创建日期：{{ createTime }}</el-col>
            </el-row>
            <el-row :gutter="20" style="margin: 20px">
              <el-col :span="12">运营人员：{{ details?.userName }}</el-col>
              <el-col
                :span="12"
              >工单类型：{{ details?.taskType?.typeName }}</el-col>
            </el-row>
            <el-row :gutter="20" style="margin: 20px">
              <el-col
                :span="12"
              >补货数量：<el-link
                type="primary"
                :underline="false"
                @click="restockDetails = true"
              >补货详情</el-link></el-col>
              <el-col
                :span="12"
              >工单方式：{{
                  details?.createType === 0
                    ? "自动"
                    : details?.createType === 1
                    ? "手动"
                    : "无"
              }}</el-col>
            </el-row>
            <el-row :gutter="20" style="margin: 20px">
              <el-col
                :span="12"
                style="margin-left: 28px"
              >备注：{{ details?.desc }}</el-col>
            </el-row>
            <div style="margin: 0 40%">
              <el-popconfirm
                placement="top"
                :visible-arrow="false"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="取消工单后，将不能恢复，是否确认取消？"
                @onConfirm="cancelTicket('cancel', details, details.taskId)"
              >
                <el-button
                  slot="reference"
                  style="background-color: #fbf4f0"
                >取消工单</el-button>
              </el-popconfirm>
            </div>
          </div>
          <div v-else>
            <div class="tickets">
              <div style="display: flex; align-items: center">
                <img
                  src=""
                  alt=""
                >
                <div style="margin-left: 20px">取消</div>
              </div>
              <div style="margin-right: 60px">
                <img
                  src="https://likede2-admin.itheima.net/img/pic_3.e8208e34.png"
                  alt=""
                >
              </div>
            </div>
            <el-row :gutter="20" style="margin: 20px">
              <el-col :span="12">设备编号：{{ details?.innerCode }}</el-col>
              <el-col :span="12">创建日期：{{ createTime }}</el-col>
            </el-row>
            <el-row :gutter="20" style="margin: 20px">
              <el-col :span="12">取消日期：{{ updateTime }}</el-col>
              <el-col :span="12">运营人员：{{ details?.userName }}</el-col>
            </el-row>
            <el-row :gutter="20" style="margin: 20px">
              <el-col
                :span="12"
              >工单类型：{{ details?.taskType?.typeName }}</el-col>
              <el-col
                :span="12"
              >补货数量：<el-link
                type="primary"
                :underline="false"
                @click="restockDetails = true"
              >补货详情</el-link></el-col>
            </el-row>
            <el-row :gutter="20" style="margin: 20px">
              <el-col
                :span="12"
              >工单方式：{{
                  details?.createType === 0
                    ? "自动"
                    : details?.createType === 1
                    ? "手动"
                    : "无"
              }}</el-col>
              <el-col :span="12">取消原因：{{ details?.desc }}</el-col>
            </el-row>
            <div style="margin: 0 40%">
              <el-button
                style="background-color: #fbf4f0"
                @click="cancelTicket('agent', details, details.taskId)"
              >重新创建</el-button>
            </div>
          </div>
        </el-dialog>
      </div>
      <div class="footer">
        <!-- 分页组件 -->
        <div style="color: #dbdfe5">
          <span>共{{ +tableData.totalCount }}条记录 </span>
          <span>第 {{ tableData.pageIndex }}/{{ tableData.totalPage }} 页</span>
        </div>
        <div style="margin-right: 30px">
          <span>
            <el-button
              v-if="!flagAbove"
              style="margin-right: 20px; background-color: #d5ddf8; color: #000"
              @click="handleCurrentChange('above')"
            >上一页</el-button>
            <el-button
              v-else
              style="
                margin-right: 20px;
                background-color: #edf0f9;
                color: #dcdde3;
              "
              disabled
            >上一页</el-button>
          </span>
          <span>
            <el-button
              v-if="!flagUnder"
              style="background-color: #d5ddf8; color: #000"
              @click="handleCurrentChange('under')"
            >下一页</el-button>
            <el-button
              v-else
              style="background-color: #edf0f9; color: #dcdde3"
              disabled
            >下一页</el-button>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { list, channelList, ticketCancel } from '@/api/workTickets'

export default {
  name: 'WorkTickets',
  data() {
    return {
      flag: true,
      manifest: false,
      loading: false,
      dialogVisible: false,
      disposition: false,
      seeDetails: false,
      restockDetails: false,
      queryObj: {
        pageIndex: 1, // 控制当前页
        pageSize: 10, // 控制每页有几条数据
        taskCode: null,
        status: null
      },
      form: {
        createType: 1,
        innerCode: null,
        userId: '',
        productType: null,
        desc: null,
        details: {
          channelCode: '',
          expectCapacity: 1,
          skuId: '',
          skuName: '',
          skuImage: ''
        }
      },
      user: [],
      // 验证规则
      rules: {
        innerCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        productType: [{ required: true, message: '请选择', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      num: 50,
      sum: null,
      rule: {
        sum: [{ required: true, trigger: 'blur' }]
      },
      tableData: {},
      list: [],
      replenishmentlist: [],
      detaillist: [],
      details: {},
      createTime: '',
      updateTime: ''
    }
  },
  computed: {
    flagAbove() {
      return this.queryObj.pageIndex <= 1
    },
    flagUnder() {
      return this.queryObj.pageIndex >= this.tableData.totalPage
    }
  },
  async created() {
    this.initTable()
  },
  methods: {
    // 渲染列表
    async initTable() {
      this.loading = true
      const data = await list(this.queryObj)
      this.tableData = data
      this.list = data.currentPageRecords
      this.list.forEach((item, index) => {
        item.index =
          (this.queryObj.pageIndex - 1) * this.queryObj.pageSize + index + 1
      })
      this.loading = false
    },
    // 查询功能
    onSubmit() {
      this.initTable()
      this.queryObj.taskCode = null
      this.queryObj.status = null
    },
    // 编号详情
    async built() {
      const data = this.list.filter(
        (item) => item.innerCode === this.form.innerCode
      )
      this.user = data
    },
    // 补货清单
    async Replenishment() {
      try {
        await this.$refs.form.validateField('innerCode')
        this.dialogVisible = false
        this.manifest = true
        const data = await channelList(this.form.innerCode)
        this.replenishmentlist = data
        this.replenishmentlist.forEach((item) => {
          this.$set(item, 'quantity', item.maxCapacity - item.currentCapacity)
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 补货数量
    handleChange(value) {},
    // 新增工单
    async submit() {
      try {
        await this.$refs.form.validate()
        // await createTickets(this.form)
        this.$message.success('添加成功')
        this.dialogVisible = false
        this.$refs.form.resetFields()
      } catch (error) {
        console.log(error)
      }
    },
    configureCommits() {
      this.$message.success('配置成功')
      this.disposition = false
      this.num = 50
    },
    // 查看详情
    async detail(row) {
      this.seeDetails = true
      const data = await channelList(row.innerCode)
      this.detaillist = data
      if (row.taskStatusTypeEntity.statusName === '待办') {
        this.flag = true
      } else {
        this.flag = false
      }
      this.details = row
      this.createTime =
        row.createTime.substring(0, 4) +
        '.' +
        row.createTime.substring(5, 7) +
        '.' +
        row.createTime.substring(8, 10) +
        ' ' +
        row.createTime.substring(11, 19)
      this.updateTime =
        row.updateTime.substring(0, 4) +
        '.' +
        row.updateTime.substring(5, 7) +
        '.' +
        row.updateTime.substring(8, 10) +
        ' ' +
        row.updateTime.substring(11, 19)
    },
    // 工单详情
    async cancelTicket(type, row, id) {
      if (type === 'cancel') {
        await ticketCancel({ taskId: id, desc: '工单超时' })
        this.$message.success('修改成功')
        this.seeDetails = false
        this.initTable()
      }
      if (type === 'agent') {
        this.seeDetails = false
        this.dialogVisible = true
        this.form.innerCode = row.innerCode
        this.form.productType = row.taskType.typeName
        this.form.userId = row.userName
        this.form.desc = row.desc
      }
    },
    // 分页功能
    async handleCurrentChange(val) {
      if (val === 'above') {
        this.queryObj.pageIndex--
        this.initTable()
      }
      if (val === 'under') {
        this.queryObj.pageIndex++
        this.initTable()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-drawer_header span:focus {
  outline: 0;
}
.box {
  background-color: #f8fafd;
  padding: 20px;
  .header {
    width: 100%;
    background-color: #fff;
    padding: 20px 0 0 20px;
    height: 80px;
    margin-bottom: 20px;
    .cha {
      background-color: #5f84ff;
    }
  }
  .body {
    background-color: #fff;
    padding: 20px 0 0 20px;
    .body-btn {
      margin-bottom: 20px;
      .xin {
        background-color: #ff6725;
      }
      .gong {
        background-color: #fbf4f0;
        color: #000;
      }
    }
  }
  .footer {
    margin-top: 30px;
    display: flex;
    justify-content: space-between;
  }
}
.tickets {
  width: 550px;
  height: 60px;
  background-color: #f8f8f8;
  margin: 0 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}
</style>
